//
//  THHomeViewController.swift
//  Practise
//
//  Created by flower on 2017/8/21.
//  Copyright © 2017年 lalala. All rights reserved.
//

import UIKit

// 定义全局常量, 尽量使用 private 修饰, 否则到处都可以访问
private let cellId = "cellId"

class THHomeViewController: THBaseViewController {
    
    /// 微博数据数组
    //fileprivate lazy var statusList = [String]()
    // 列表视图模型
    fileprivate lazy var listViewModel = THStatusListViewModel()
    
    /// 加载数据
    override func loadData() {
        
        print("准备刷新,最后一条 \(self.listViewModel.statusList.last?.text)")
        listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
            
             print("加载数据结束")
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            // 恢复上拉刷新标记
            self.isPullup = false
            // 刷新表格
            if shouldRefresh {
                 self.tableView?.reloadData()
            }
           
            
        }
        
//        // 用网络工具加载微博数据
//        THNetworkManager.shared.statusList {(list, isSuccess) in
//            print("加载数据完成 \(list)")
//        }
        
        
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token": "2.00dPzaQDgnAdrDaa48e67db0VnE5fD"]
//        
//        THNetworkManager.shared.request(URLString: urlString, parameters: params) { (
//            json, isSuccess) in
//            
//            print(json ?? "")
//        }
        
//        THNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (
//            _, json) in
//            print(json ?? "")
//        }) { (
//            _, error) in
//            print("网络请求失败 \(error)")
//        }
        
//        print("开始加载数据 \(THNetworkManager.shared)")
//        
//        // 模拟`延时`加载数据  dispatch_after
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) {
//            
//            for i in 0..<20 {
//                
//                if self.isPullup {
//                    self.statusList.append("上拉\(i)")
//                } else {
//                    // 将数据插入到数组的顶部
//                    self.statusList.insert(i.description, at: 0)
//                }
//            }
//            
//            
//            print("加载数据结束")
//            // 结束刷新控件
//            self.refreshControl?.endRefreshing()
//            // 恢复上拉刷新标记
//            self.isPullup = false
//            // 刷新表格
//            self.tableView?.reloadData()
//        }
        
      
    }
    
    /// 显示好友
   @objc fileprivate func showFriends() {

        print(#function)
        
        let vc = THDemoViewController()
        
        //vc.hidesBottomBarWhenPushed = true
        // push 的动作是 nav 做的
        navigationController?.pushViewController(vc, animated: true)
        
    }
}


// MARK: - 表格数据源方法
extension THHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       // return statusList.count
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 1. 取 cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        // 2. 设置 cell
        //cell.textLabel?.text = statusList[indexPath.row]
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        // 3. 返回 cell
        return cell
        
    }
}


// MARK: - 设置页面
extension THHomeViewController {
    
    
    /// 重写父类的方法
    override func setupTableView() {

        super.setupTableView()
        
        // 设置导航栏按钮
        // 无法高亮
        // navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
        
        // Swift 调用 OC 返回 instancetype 的方法, 判断不出是否可选
        //let btn: UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.orange)
        //btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
        
        //navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
        
        // 抽取出 UIBarButtonItem  设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        // 注册原型 cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        
        setNavTitle()
        
    }
    
    // 设置导航栏标题
    private func setNavTitle() {
        
        let title = THNetworkManager.shared.userAccount.screen_name
//        let button = UIButton.cz_textButton(title, fontSize: 17, normalColor: UIColor.darkGray, highlightedColor: UIColor.black)
//        
//        button?.setImage(UIImage(named: "navigationbar_arrow_down"), for: [])
//        button?.setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        
        let button = THTitleButton(title: title)
        navItem.titleView = button
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    
    }
    
    @objc func clickTitleButton(btn: UIButton) {
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
}
